import Vue from 'vue'
import Vuex from 'vuex'
import api, {
	getQueryObject
} from '@/common/util.js'
import {
	userLogin
} from '@/common/api.js'
import {
	//MessageStatistics
} from '@/common/api'
Vue.use(Vuex);
// #ifdef H5
//window.localStorage.setItem('super_token','eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwczpcL1wvcHJvZHVjZS5qc3R4bS5jblwvd2VjaGF0XC8iLCJhdWQiOiJodHRwczpcL1wvcHJvZHVjZS5qc3R4bS5jblwvd2VjaGF0XC8iLCJpYXQiOjE2MTM2MzU5MzMsIm5iZiI6MTYxMzYzNTkzMywiZXhwIjoxNjEzNjc5MTMzLCJ1aWQiOjIwN30.');
const openid = window.localStorage.getItem('super_token');

// #endif
// 非H5端
//#ifndef H5
const openid = uni.getStorageSync('super_token');
//#endif
const store = new Vuex.Store({
	state: {
		openid: openid,
		hasLogin: openid ? true : false, //是否登录
		userInfo: uni.getStorageSync('userInfo'), //用户信息
		indexSub: uni.getStorageSync('indexSub'), //首页导航
		themeName:uni.getStorageSync('themeName'),
		share_id: '', // 分享上级id
		agent_id: '', // 代理id
		unread_num: '0'
	},
	mutations: {
		//登录
		login(state) {
			handleLogin(state);
		},
		setLogin(state, login) {
			state.openid = login
		},
		setloginStatus(state, status) {
			state.hasLogin = status
		},
		setShareId(state, data) {
			if (data.share_id) {
				state.share_id = data.share_id
			}
			if (data.agent_id) {
				state.agent_id = data.agent_id
			}
		},
		// 设置用户信息
		setUserInfo(state, userInfo) {
			if (userInfo) {
				state.userInfo = userInfo
			} // 小程序用户信息 用户授权获取
		},
		// 设置用户信息
		setIndexSub(state, indexSub) {
			if (indexSub) {
				state.indexSub = indexSub
			} // 储存首页用户选的indexSub
		},
		// 设置用户信息
		setthemeName(state, themeName) {
			if (themeName) {
				state.themeName = themeName
			} // 储存首页用户选的themeName
		},
		loginOut(state) {
			state.hasLogin = false;
			state.openid = '';
			// #ifdef H5
			window.localStorage.removeItem('super_token')
			uni.switchTab({
				url: `/pages/index/index`
			})
			// #endif
			//#ifdef MP
			uni.removeStorageSync('super_token');
			uni.removeStorageSync('userInfo');
			uni.removeStorageSync('themeName');
			// #endif
			// #ifdef APP-PLUS
			uni.removeStorageSync('super_token')
			// #endif
		},
		// 获取未读消息的数量
		get_unread(state) {
			/* MessageStatistics({
				token: state.token
			}).then(res => {
				uni.setStorage({
					key: 'unReadNum',
					data: res.data.unread_msg_num
				})
				state.unread_num = res.data.unread_msg_num > 99 ? '99' : res.data.unread_msg_num
					.toString();
				if (state.unread_num == 0) {
					uni.removeTabBarBadge({
						index: 1
					})
				} else {
					uni.setTabBarBadge({
						index: 1,
						text: state.unread_num
					})
				}
			}); */
		}
	}
})

function handleLogin(state) {
	//#ifdef H5
	// h5登陆 -> 发送url给后台，后端把openid 写在本地localStorage中
	const str = window.appConfig.apiUrl.replace(/wechat\//, '');
	const URI = encodeURIComponent(str + 'index.html?#/');
	let url = '';
	console.log('getQueryObject()--->', getQueryObject());
	const agent_id = state.agent_id;
	if (getQueryObject() && getQueryObject().share_id) {
		const referee_uid = getQueryObject().share_id;
		url = `${window.appConfig.apiUrl}Login/Login?re_uri=${URI}&login_type=8&referee_uid=${referee_uid}`
	} else if (agent_id) {
		url = `${window.appConfig.apiUrl}Login/Login?re_uri=${URI}&login_type=8&agent_id=${agent_id}`
	} else {
		url = `${window.appConfig.apiUrl}Login/Login?re_uri=${URI}&login_type=8`
	}
	console.log('url--->', url);
	window.location.href = url;
	//#endif

	//#ifdef MP
	/* uni.login({
		// #ifdef MP-WEIXIN
		provider: 'weixin',
		// #endif
		success(loginRes) {
			const {
				code
			} = loginRes
			// #ifdef MP-WEIXIN
			const login_type = 9
			// #endif
			getopenids({
				code
			}).then(({
				data
			}) => {
				const {
					openid
				} = data;
				state.openid = openid
				uni.setStorageSync('super_token', openid);
				state.hasLogin = true
				uni.navigateTo({
					url: '/pages/public/tologin'
				})
			})
		},
		fail(e) {
			console.log('errer->', e)
		}
	}); */
	uni.login({
		success: (res) => {
			// 获取用户信息
			uni.getUserInfo({
				provider: 'weixin',
				success: function(infoRes) {
					console.log(3333, infoRes);
				}
			});
			if (res.errMsg == "login:ok") {
				const code = res.code;
				console.log(2222, code)
				userLogin({
					code
				}).then(resData => {
					console.log(1111, resData)
				})
			} else {
				uni.showToast({
					title: "系统异常，请联系管理员！"
				})
			}
		}
	});
	/* uni.login({
		success(loginRes) {
			const { code } = loginRes
			// #ifdef MP-WEIXIN
			const login_type = 2
			// #endif
			// #ifdef MP-TOUTIAO
			//const login_type = 4
			// #endif
			userLogin({ code }).then(({data}) => {
				console.log(222333)
				const { openid } = data;
				state.openid = openid
				 uni.setStorageSync('super_token', openid);
				state.hasLogin = true
				handleAddcar();
				uni.navigateTo({
					url: `/pages/public/tologin`
				});
			})
		},
		fail(e) {
			console.log('errer->',e)
		}
	}); */
	//#endif

	// #ifdef APP-PLUS
	// isLogin()
	const login_type = 11;
	uni.login({
		provider: 'weixin',
		success: function(loginRes) {
			console.log('App微信获取用户信息成功', loginRes);
			userLogin({
				openid: loginRes.authResult.openid,
				access_token: loginRes.authResult.access_token,
				login_type,
				referee_uid: state.share_id
			}).then(({
				data
			}) => {
				console.log(data, '获取到openid')
				const {
					openid
				} = data;
				state.openid = openid
				uni.setStorageSync('super_token', openid);
				state.hasLogin = true
				uni.switchTab({
					url: `/pages/index/index`
				})
				uni.showToast({
					title: '登录成功',
					duration: 1000
				});
				uni.$emit('refresh')
			}).catch(err => {
				console.log(err, 'app获取数据失败')
			})
		},
		fail: function(res) {
			console.log('App微信获取用户信息失败', res);
			uni.showToast({
				title: res,
				duration: 3000
			});
		}
	});
	//#endif
}
// app获取code
// #ifdef APP-PLUS
function appLogin() {
	return new Promise((resolve, reject) => {
		// 判断设备上是否安装微信
		const auths = {}
		plus.oauth.getServices(function(services) {
			for (var i in services) {
				auths[services[i].id] = services[i];
			}
			// 获取微信
			const aweixin = auths['weixin'];
			authorize(aweixin)
		}, function(err) {
			reject(err)
			console.log("获取登录授权服务列表失败：" + JSON.stringify(err));
		});

		function authorize(aweixin) {
			if (!aweixin) {
				plus.nativeUI.alert("当前环境不支持微信登录,请前往下载微信");
				return
			}
			aweixin.authorize((e) => {
				console.log("授权成功：" + JSON.stringify(e));
				resolve(e)
			}, function(err) {
				console.log("授权失败：" + JSON.stringify(err));
				reject(err)
			}, {
				scope: 'snsapi_userinfo',
				state: 'super-assemble'
			});
		}
	})
}
// #endif
// #ifdef APP-PLUS
function isLogin() {
	// 判断设备上是否安装微信
	const auths = {}
	plus.oauth.getServices(function(services) {
		for (var i in services) {
			auths[services[i].id] = services[i];
		}
		// 获取微信
		const aweixin = auths['weixin'];
		authorize(aweixin)
	}, function(err) {
		reject(err)
		console.log("获取登录授权服务列表失败：" + JSON.stringify(err));
	});
}

function authorize(aweixin) {
	if (!aweixin) {
		plus.nativeUI.alert("当前环境不支持微信登录,请前往下载微信");
		return
	}
}
// #endif
export default store
